HC = ghc
MAKELAGS = --make
OPTIMIZE = -O

ALEXFLAGS = --ghc
HAPPYFLAGS = --ghc

PARSERCOUTPUT = ./parser
LPOUTPUT = ./lp

SUBDIRS = Common Modtool Compiler

# default target (when not specifying)
DEFAULT=debug

ifeq ($(CFG),)
CFG=$(DEFAULT)
endif

all: parser subdirs modtool compiler
	@echo -e "\n ************\n * All done *\n ************"

.PHONY: subdirs $(SUBDIRS)
 
subdirs: $(SUBDIRS)
     
$(SUBDIRS):
	$(MAKE) -C $@

modtool: subdirs
	@cp Modtool/$(CFG)/modtool ./modtool

compiler: subdirs
	@cp Compiler/$(CFG)/compiler ./compiler

parser: Parser/build Parser/build/Lexer.hs Parser/Parser.hs Parser/Main.hs
	@$(HC) -iParser -iParser/build -hidir Parser/build -odir Parser/build $(MAKELAGS) $(OPTIMIZE) Parser/Main.hs -o $(PARSERCOUTPUT)

Parser/build/Lexer.hs: Parser/build/Lexer.x | Parser/build
	alex $(ALEXFLAGS) Parser/build/Lexer.x -o Parser/build/Lexer.hs

Parser/build/Lexer.x: lp Parser/tokens.lpt Parser/Lexer.ux | Parser/build
	@$(LPOUTPUT) Parser/tokens.lpt Parser/Lexer.ux Parser/build/Lexer.x

Parser/build: 
	@mkdir Parser/build

etc-clean-build:
	@rm -rf Parser/build

etc-clean: etc-clean-build
	@rm -rf $(PARSERCOUTPUT)

lp: LexProcessor/build LexProcessor/build/LPParser.hs LexProcessor/Main.hs
	@$(HC) -iLexProcessor/build -hidir LexProcessor/build -odir LexProcessor/build $(MAKELAGS) $(OPTIMIZE) LexProcessor/Main.hs -o $(LPOUTPUT)

LexProcessor/build: 
	@mkdir LexProcessor/build

lp-clean-build: 
	@rm -rf LexProcessor/build

lp-clean: lp-clean-build
	@rm -rf $(LPOUTPUT)

LexProcessor/build/LPParser.hs: LexProcessor/LPParser.y | LexProcessor/build
	happy $(HAPPYFLAGS) LexProcessor/LPParser.y -o LexProcessor/build/LPParser.hs

clean: etc-clean lp-clean
	@cd Compiler && make clean && cd ..
	@cd Common && make clean && cd ..
	@cd Modtool && make clean && cd ..
	@rm -f compiler
	@rm -f modtool

